package com.softeem.servlet;

import com.google.gson.Gson;
import com.softeem.bean.Book;
import com.softeem.service.BookService;
import com.softeem.service.impl.BookServiceImpl;
import com.softeem.utils.BaseServlet;
import com.softeem.utils.Page;
import com.softeem.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet(value="/BookServlet")
public class BookServlet extends BaseServlet {
    protected void searchPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String name = req.getParameter("name");
        String author = req.getParameter("author");
        Double min = WebUtils.parseDouble(req.getParameter("min") , -1);
        Double max = WebUtils.parseDouble(req.getParameter("max") , -1);
        Integer pageNo = WebUtils.parseInt(req.getParameter("pageNo") , 1);
        Integer pageSize = WebUtils.parseInt(req.getParameter("pageSize") , 4);

        BookService bookService = new BookServiceImpl();
        Page<Book> page = bookService.page(pageNo, pageSize, name, author, min, max);

        Gson gson = new Gson();
        //将page 转换成 json 字符串
        String str = gson.toJson(page);

        resp.setContentType("application/json;charset=utf-8");

        PrintWriter out = resp.getWriter();

        out.print(str);

        /*name = name == null ? "" : name ;
        author = author == null ? "" : author ;
        //为page对象中的url赋值
        page.setUrl("BookServlet?method=searchPage&name="+name+"&author="+author+"&min="+min+"&max="+max);
        req.setAttribute("page" , page);
        req.setAttribute("name" ,name);
        req.setAttribute("author" , author);
        req.setAttribute("min" , min == -1 ? null : min);
        req.setAttribute("max" , max == -1 ? null : max);
        req.getRequestDispatcher("/first.jsp").forward(req,resp);*/
    }



    protected void getBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ,SQLException{
        //创建book业务层对象 :bookService
        BookService bookService = new BookServiceImpl();
        //通过request对象获取网页提交上来的id参数.但是它默认是String类型.所以我们将它转换成int类型
        Integer id = WebUtils.parseInt(req.getParameter("id"), 0);
        //网页修改的a连接将pageNo提交到了getBook方法中.但是getBook方法并不需要使用pageNo参数.而是我们的的page方法需要使用pageNo参数
        //int pageNo = WebUtils.parseInt( req.getParameter("pageNo"),1);

        //调用booService对象中的queryBookById方法.通过id查询出book对象
        Book book = bookService.queryBookById(id);
        //将book对象保存到request请求域中
        req.setAttribute("book" , book);

        //服务器转发到/pages/manager/book_edit.jsp网页,并且request请求域中的数据发送到网页
        req.getRequestDispatcher("/pages/manager/book_edit.jsp").forward(req,resp);
    }


    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ,SQLException{
        //创建book业务层对象 :bookService
        BookService bookService = new BookServiceImpl();

        //调用bookService层中的queryBooks方法得到一个bookList集合
        List<Book> bookList = bookService.queryBooks();

        //将bookList集合添加到request请求域中
        req.setAttribute("bookList" , bookList);

        //请求转发到/pages/manager/manager.jsp网页,这样可以将request请求域中的数据传递到jsp网页
        req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req,resp);
    }

    protected void saveOrUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException,SQLException {
        BookService bookService = new BookServiceImpl();
        //判断form表单 是否设置了 enctype="multipart/form-data"
        if(ServletFileUpload.isMultipartContent(req)) {
            //创建FileItemFactory 工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            // 创建用于解析上传数据的工具类ServletFileUpload 类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            Book book = new Book();//瞬时
            try {
                int pageNo = 1 ;
                // 解析上传的数据，得到每一个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(req);
                //循环这6段数据并处理它们
                for (FileItem fileItem : list) {
                    //判断那些是普通表单项,还是上传的文件类型
                    if (fileItem.isFormField()) {
                        //处理普通表单项
                        //System.out.println(fileItem.getFieldName() +" = " + MyUtils.parseString(fileItem.getString()));
                        if("id".equals(fileItem.getFieldName())){
                            book.setId( WebUtils.parseInt(fileItem.getString() , 0));
                            if(book.getId() != 0) {
                                //持久
                                book = bookService.queryBookById(book.getId());
                            }
                        }else if("pageNo".equals(fileItem.getFieldName())){
                            pageNo = WebUtils.parseInt(fileItem.getString() , 1);
                        }else if ("name".equals(fileItem.getFieldName())) {
                            book.setName(fileItem.getString("utf-8"));//图书名
                        } else if ("author".equals(fileItem.getFieldName())) {
                            book.setAuthor(fileItem.getString("utf-8"));//图书作者
                        } else if ("price".equals(fileItem.getFieldName())) {
                            book.setPrice(Double.parseDouble(fileItem.getString()));//图书价格
                        } else if ("sales".equals(fileItem.getFieldName())) {
                            book.setSales(Integer.valueOf(fileItem.getString()));//图书销量
                        } else if ("stock".equals(fileItem.getFieldName())) {
                            book.setStock(Integer.parseInt(fileItem.getString()));//图书库存
                        }
                    } else {
                        //如果大于0就证明选择了图片,
                        if(fileItem.getSize() > 0) {

                            //处理文件类型(文件上传)
                            String filename = fileItem.getName();//获取文件名
                            //文件名 = 123.jpg       suffix = .jpg
                            String suffix = filename.substring(filename.lastIndexOf("."));
                            //通过时间毫秒 + 后缀 = 新文件名
                            String newfilename = System.currentTimeMillis() + suffix;

                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            String format = simpleDateFormat.format(new Date());
                            File file = new File("D:/JAVAIDEAR/book/web/static/bookimg/" + format + "/");
                            if (!file.exists()) {//判断要上传的文件目录是否存在
                                file.mkdirs();//创建目录
                            }
                            System.out.println(file.getAbsolutePath());
                            fileItem.write(new File(file, newfilename));//上传图片

                            //上传成功完老图片删除掉
                            File deleteFile = new File("D:/JAVAIDEAR/book/web/"+book.getImgPath());
                            deleteFile.delete();
                            book.setImgPath("static/bookimg/" + format + "/" + newfilename);//图书封面
                        }
                    }
                }
                //调用bookService中saveOrUpdate方法.添加图书信息
                bookService.saveOrUpdate(book);

                //第一种
                //req.getRequestDispatcher("/BookServlet?method=list").forward(req,resp);
                //第二种
                //this.list(req,resp);
                //第三种方式
                resp.sendRedirect("BookServlet?method=page&pageNo=" + pageNo);//前面不要加斜杠
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ,SQLException{
        //创建book业务层对象 :bookService
        BookService bookService = new BookServiceImpl();
        //通过request对象获取网页提交上来的id参数.但是它默认是String类型.所以我们将它转换成int类型
        Integer id =  WebUtils.parseInt(req.getParameter("id") , 0);
        //网页删除的a连接将pageNo提交到了delete方法中.但是delete方法并不需要使用pageNo参数.而是我们的的page方法需要使用pageNo参数
        //Integer pageNo = WebUtils.parseInt(req.getParameter("pageNo") , 1);
        //调用bookService中的deleteBookById方法..通过主键id删除数据
        bookService.deleteBookById(id);
        //第一种
        //req.getRequestDispatcher("/BookServlet?method=list").forward(req,resp);
        //第二种
        this.page(req,resp);
    }

    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException,SQLException {
        //获取当前页,如果获取不到.那么默认设置成1
        int pageNo = WebUtils.parseInt( req.getParameter("pageNo"),1);
        //获取当pageSize,如果获取不到.那么默认设置成5
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"),5);
        //创建book业务层对象 :bookService
        BookService bookService = new BookServiceImpl();
        Page<Book> page = bookService.page(pageNo, pageSize);
        page.setUrl("BookServlet?method=page");
        // 将page对象保存request请求域中
        req.setAttribute("page" ,page);
        //请求转发到/pages/manager/manager.jsp网页,这样可以将request请求域中的数据传递到jsp网页
        req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req,resp);
    }
}
